﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

namespace MM.Translator.Model
{
    public class BingTranslationProvider : ITranslationProvider
    {
        public void Translate(string inputText, string fromLanguage, string toLanguage)
        {
            const string appId = "F63F51889200EA76E5F2FC9A59F1FF933D548754";
            var url = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" + appId + "&text=" + inputText + "&from=" + fromLanguage + "&to=" + toLanguage;

            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            webClient.DownloadStringCompleted += OnDownloadStringCompleted;
            webClient.DownloadStringAsync(new Uri(url));
        }

        private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (TranslationCompleted != null)
            {
                if (e.Error != null)
                {
                    TranslationCompleted(this, new TranslationEventArgs { Error = e.Error });
                    return;
                }

                var result = e.Result;
                var serializer = new XmlSerializer(typeof(string), "http://schemas.microsoft.com/2003/10/Serialization/");
                var resultText = (string)serializer.Deserialize(new StringReader(result));

                TranslationCompleted(this, new TranslationEventArgs { Result = resultText });
            }
        }

        public event EventHandler<TranslationEventArgs> TranslationCompleted;
    }
}